<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

use App\Models\Cat;
use App\Models\Searchhis;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;
	
	
	protected $cats;

    public function __construct()
    {
		if (!Cache()->has('cats')) {
			$cats = array_column(Cat::select('cat_id','catname','pinyin')->get()->toArray() , null , 'cat_id');
			Cache()->set('cats',$cats,3800);
		}
        $this->cats = Cache()->get('cats');
		//视图全局
		\View::share('cats', $this->cats);
		//热门搜索-取7天的数据去重
		\View::share('searchhis', Searchhis::select('keywords')->where('created_at','>',date('Y-m-d',strtotime('-7 day', time())))->groupBy('keywords')->orderByDesc('created_at')->limit(5)->get()->toArray());
    }
	
	
	/**
	 * 目前用于文章详情页的评论数据重新生成子孙树结构
	 *
     * 无极限分类 ：一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id 父ID Key
     * @param string $pid ID Key
     * @param string $son 定义子数据Key
     * @return Collection
     */
    public function sontree_comment($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        list($tree, $map) = [[], []];
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }

        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }
	
}
